package com.zhiren.settlement;

import com.zhiren.formular.Calculator;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SettleMentTestUtil {
    public static final String REG_PATTERN_SPLIT = "\\}\\s*,\\s*\\{";
    public static final String REG_PATTERN_BRACKET = "\\{[^{]*\\}";
    public static final String REG_PATTERN_CONTENTOPEN = "^\\[\\s*\\{";
    public static final String REG_PATTERN_CONTENTCLOSE = "\\}\\s*\\]$";
    public static final String REG_PATTERN_COMMA = ",";
    public static final String REG_PATTERN_TILDE = "`~";
    public static final String REG_PATTERN_EQUAL = "=";
    public static final String REG_PATTERN_FORMULAPARAM_BEGIN = "[f|F][o|O][r|R][m|M][u|U][l|L][a|A][p|P][a|A][r|R][a|A][m|M]";
    public static final String REG_PATTERN_FORMULAPARAM_END = ",\\s[g|G][r|R][o|O][u|U][p|P][n|N][u|U][m|M]";
    public static final String REG_PATTERN_FORMULAPARAM = REG_PATTERN_FORMULAPARAM_BEGIN + ".*" + REG_PATTERN_FORMULAPARAM_END;

    /**
     * 获取全部公式代表的
     * @param strFormula
     * @return
     */
    private static List<String> getRegList(String strFormula){
        List<String> strLsit = new ArrayList();
        String[] strPatternArr = {
                Calculator.REG_PATTERN_ABS,
                Calculator.REG_PATTERN_CEIL,
                Calculator.REG_PATTERN_DECODE,
                Calculator.REG_PATTERN_FLOOR,
                Calculator.REG_PATTERN_IF,
                Calculator.REG_PATTERN_ROUND,
                Calculator.REG_PATTERN_ROUNDNEW
        };
        int idead = 100000;
        Boolean isContinue = false;
//        List<String> strLsitTmp;
        while(true){
            for(String strPattern: strPatternArr){
                //获取符合正则的内容
                List<String>  strLsitTmp = getRegList4Pattern(strFormula, strPattern);
                //判定是否继续
                isContinue = isContinue==false?strLsitTmp.size()>0:true;
                //替换语句
                strFormula = replaceFromList(strFormula, strLsitTmp, strLsit.size());
                //替换内容整体加入list
                strLsit.addAll(strLsitTmp);
            }
            if(idead--<0 || !isContinue){
                break;
            }
        }
        return strLsit;
    }

    /**
     * 根据序号构造替换字符串
     * @param icount
     * @return
     */
    private static String getStrSign(int icount){
        return "${"+icount+"}";
    }

    /**
     * 替换字符串内容，原内容包含在strRegLsit中，新内容为替代符号
     * @param strFormula
     * @param strRegLsit
     * @param icount
     * @return
     */
    private static String replaceFromList(String strFormula, List<String> strRegLsit, int icount){
        String strReturn = strFormula;
        for(String strOld: strRegLsit){
            String strNew = getStrSign(icount++);
            strReturn = strReturn.replace(strOld, strNew);
        }
        return strReturn;
    }

    private static String replaceListReverse(String strFormula, List<String> strRegLsit){
        String strReturn = strFormula;
        for(int i= strRegLsit.size()-1; i>=0; i--){
            String strNew = getStrSign(i);
            String strOld = strRegLsit.get(i);
            strOld = strOld.replaceAll(REG_PATTERN_COMMA, REG_PATTERN_TILDE);
            strReturn = strReturn.replace(strNew, strOld);
        }
        return strReturn;
    }

    /**
     * 根据正则获取字符串匹配内容的列表
     * @param strFormula
     * @param strPattern
     * @return
     */
    private static List<String> getRegList4Pattern(String strFormula, String strPattern){
        List<String> strLsit = new ArrayList<String>();
        Pattern r = Pattern.compile(strPattern);
        Matcher m = r.matcher(strFormula);
        while(m.find()){
            strLsit.add(m.group(0));
        }
        return strLsit;
    }

    /**
     * 根据系统导出的字符串构建List
     * @param strText
     * @return
     */
    public static List<Map<String,String>> changeList4Str(String strText){
        List<Map<String,String>> reMapList = new ArrayList();
        strText = strText.replaceAll(REG_PATTERN_CONTENTOPEN,"").replaceAll(REG_PATTERN_CONTENTCLOSE,"");
        String[] strTextArr = strText.split(REG_PATTERN_SPLIT);
        for(String strTextPart: strTextArr){
            strTextPart = strTextPart.replaceAll(REG_PATTERN_BRACKET,"");
            Map tmpMap = new HashMap();
            List<String> strRegList = getRegList(strTextPart);
//            Collections.reverse(strRegList);
            strTextPart = replaceFromList(strTextPart, strRegList, 0);
            strTextPart = replaceListReverse(strTextPart, strRegList);
            //处理formulaparam  中有多个值通过逗号隔离的问题
            List<String> strParamList = getRegList4Pattern(strTextPart, REG_PATTERN_FORMULAPARAM);
            for(String strParam : strParamList){
                String strFormula = strParam.replaceAll(REG_PATTERN_FORMULAPARAM_END, "");
                String strTmp = strFormula.replaceAll(REG_PATTERN_COMMA, REG_PATTERN_TILDE);
                strTextPart = strTextPart.replaceAll(strFormula, strTmp);
            }
            String[] strFieldArr = strTextPart.split(REG_PATTERN_COMMA);
            for(String strField : strFieldArr){
                strField = strField.replaceAll(REG_PATTERN_TILDE, REG_PATTERN_COMMA);
                int ibegin = strField.indexOf(REG_PATTERN_EQUAL);
                if(ibegin>0){
                    String strKey =  strField.substring(0,ibegin);
                    String strValue = strField.substring(ibegin+1);
                    strKey = strKey==null||"null".equals(strKey)?null:strKey.trim();
                    strValue = strValue==null||"null".equals(strValue)?null:strValue.trim();
                    tmpMap.put(strKey, strValue);
                }
            }
            reMapList.add(tmpMap);
        }
        return reMapList;
    }

    /**
     * 根据传入的字符串类的结算方案内容构建结算方案Bean
     * @param strGroup          结算分组
     * @param strPriceTerms     结算计价
     * @param strDeduction      结算増扣
     * @return
     * @throws UnsupportedEncodingException
     */
    public static SettlementTemplate changeTemp4Str(String strGroup, String strPriceTerms, String strDeduction) throws UnsupportedEncodingException {
        List<Map<String,String>> GroupList = changeList4Str(strGroup);
        List<Map<String,String>> PriceTermsList = changeList4Str(strPriceTerms);
        List<Map<String,String>> DeductionList = changeList4Str(strDeduction);
        return new SettlementTemplate(GroupList, PriceTermsList, DeductionList);
    }
}
